//#include <stdio.h>
#include <math.h>
#include "user.h"
#include "user_doe.h"

//static double a,b,d,d1,wl,s, f,angle,Cos;
static double a,b,d,d1,wl,s, f;
static int sign, N;

double KvaziDOE_Fun(double u, double v) {
double c, ph;
c = M_PI/(wl*f);
int i1 = (u+a/2)/(a/N);
int j1 = (v+b/2)/(b/N);
double ul=(u+a/2)-i1*a/N-a/N/2;
double vl=(v+b/2)-j1*b/N-b/N/2;
ph = c*(ul*ul*(d*N)/a+vl*vl*(d1*N)/b);
ph+= M_PI*( i1*i1+j1*j1 )/N;

  if(sign) return ph;
  else     return (ph-c*(u*u+v*v));

}

//double KvaziDOE_Fun1(double u,double v) {
//return KvaziDOE_Fun(Cos*u,v);
//}

void KvaziDOE_MinMax(double *min, double *max) {

if(sign) { *min=0; *max=KvaziDOE_Fun(a/2,b/2);  }
else     { *min=KvaziDOE_Fun((a-a/N)/2,(b-b/N)/2);
	   *max=KvaziDOE_Fun(0,0); }
}

void KvaziDOE()   {
   char *InputValues[9];
   char *Title={"Beam Shaper: Kvazi DOE"};
   char *Default[]={"12.8      ",
		    "12.8      ",
		    "2         ",
		    "2         ",
		    "2         ",
		    "500       ",
		    "1.06      ",
		    ".1        ",
  //                  "0         ",
		    "1         "};
   char *ParNames[]={"Width              :",
		     "Hight              :",
		     "Hor. Rectan. Size  :",
		     "Ver. Rectan. Size  :",
		     "Subelement Number  :",
		     "Focal  Length      :",
		     "WaveLength (micron):",
		     "Discretization Step:",
    //                 "Angle              :",
		     "With Lens/Else  0/1:"};
   if(!sedit(25,5,9,ParNames,InputValues,Default,Title))  return ;

   // read input data
   sscanf(InputValues[0],"%lf",&a);   sprintf(Default[0],"%f",a);
   sscanf(InputValues[1],"%lf",&b);   sprintf(Default[1],"%f",b);
   sscanf(InputValues[2],"%lf",&d);   sprintf(Default[2],"%f",d);
   sscanf(InputValues[3],"%lf",&d1);  sprintf(Default[3],"%f",d1);
   sscanf(InputValues[4],"%d", &N);   sprintf(Default[4],"%d",N);
   sscanf(InputValues[5],"%lf",&f);   sprintf(Default[5],"%f",f);
   sscanf(InputValues[6],"%lf",&wl);  sprintf(Default[6],"%f",wl);
   sscanf(InputValues[7],"%lf",&s);   sprintf(Default[7],"%f",s);
//   sscanf(InputValues[8],"%lf",&angle);   sprintf(Default[8],"%f",angle);
//   Cos=cos(angle*M_PI/180);
   sscanf(InputValues[8],"%d",&sign); sprintf(Default[9],"%d",sign);
   wl=wl/1000;
   if( N%2!=0 ) {
     strbox("Subelement Number must be even only");
     return;
   }

   // max&min values of phase in this mask
   double min=0,max=1;
   KvaziDOE_MinMax(&min, &max);
   NonSymmetricDOE(Phase, max, min, KvaziDOE_Fun);

   if(MessageSize(a, b, s)) return;

   UndoMenu(2) ;
   MessageName(Title);
   MessageParam(1,"Size:w=%f,h=%f",a,b);
   MessageParam(2,"Rect.:w=%f,h=%f",d,d1);
   for(int i=4; i<10; i++)
      MessageParam(i-1,"%s%s",ParNames[i],Default[i]);

   MessageOut();

   return;
}
